package com.xysq.activity;
/**
 * @Author huangdongkai 2015/7/24
 * B端支付
 */

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.animation.FlipEnter.FlipVerticalSwingEnter;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.flyco.dialog.widget.NormalTipDialog;
import com.rockcent.action.CallbackListener;
import com.rockcent.model.CouponModel;
import com.rockcent.model.CustomerCouponBO;
import com.rockcent.model.OrderInfo;
import com.rockcent.model.WalletModel;
import com.rockcent.model.constant.CustomerCouponCategory;
import com.rockcent.model.constant.CustomerCouponType;
import com.rockcent.model.constant.LimitType;
import com.rockcent.model.constant.ModelType;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.umeng.analytics.MobclickAgent;
import com.xysq.XYApplication;
import com.xysq.lemon.R;
import com.xysq.util.AlipayOrderInfoBuilder;
import com.xysq.util.Base64;
import com.xysq.util.Keys;
import com.xysq.util.MD5;
import com.xysq.util.PropertiesUtil;
import com.xysq.util.Result;
import com.xysq.util.ToastUtil;
import com.xysq.util.UseUtil;
import com.xysq.util.UserInfoKeeper;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import butterknife.InjectView;


public class PayActivity extends BaseActivity implements View.OnClickListener, TextWatcher {
    @InjectView(R.id.edt_num)
    EditText numEdt;
    @InjectView(R.id.ibtn_minus)
    ImageButton miniusIbtn;
    @InjectView(R.id.ibtn_plus)
    ImageButton plusIbtn;
    @InjectView(R.id.ibtn_wallet_check)
    ImageButton walletCheckIbtn;
    @InjectView(R.id.ibtn_wechat_check)
    ImageButton wechatCheckIbtn;
    @InjectView(R.id.ibtn_alipay_check)
    ImageButton alipayCheckIbtn;
    @InjectView(R.id.txt_money)
    TextView moneyText;
    @InjectView(R.id.txt_customer_name)
    TextView nameTxt;
    @InjectView(R.id.txt_price)
    TextView priceTxt;
    @InjectView(R.id.txt_price_count)
    TextView priceCountTxt;
    @InjectView(R.id.btn_sure_pay)
    Button surePayBtn;
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.layout_empty_quan)
    RelativeLayout emptyQuanLayout;
    @InjectView(R.id.layout_quan)
    LinearLayout quanLayout;
    @InjectView(R.id.txt_quan_num)
    TextView quanNumTxt;
    @InjectView(R.id.txt_quan_name)
    TextView quanNameTxt;
    @InjectView(R.id.layout_quan_check)
    RelativeLayout quanCheckLayout;
    @InjectView(R.id.iv_is_check)
    ImageView isCheckIv;
    @InjectView(R.id.layout_loading)
    LinearLayout loadingLayout;
    @InjectView(R.id.layout_reloading)
    LinearLayout reloadingLayout;

/*    private static final int MESSAGE_ALIPAY = 0;
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private String payInfo;*/
    private String loginName;
    private int channelId = 0;
    private String payType = "wechat";
    private int couponModelId;
    private CouponModel couponModel;
    private CustomerCouponBO customerCouponBO;
    private int count = 1;//初始化为一张
    public final static String COUPON_CATEGORY = "couponCategory";
    public final static String COUPON_MODEL_ID = "couponModelId";
    public final static String ORDER_NUMBER = "orderNumber";
    private final String DISCOUNT = "discount";
    private final String VOUCHER = "voucher";
    private String orderNumber;
    private String canUseDataList[];
    private int canUseDataIdList[];
    private String quanName;//优惠券名字
    private int quanId = 0;//优惠券ID
    private double preferentialPrice = 0;//优惠字段,默认无优惠
    private String preferentialType = "cash";//DISCOUNT为折扣券，VOUCHER为抵扣券
    private Map<Object, Object> map = new HashMap<>();
    double priceCount = 0;
    private double walletMoney = 0;
    private CustomerCouponCategory couponCategory;
    private boolean isOverLimit = true;

    BaseAnimatorSet bas_in = new FlipVerticalSwingEnter();
    BaseAnimatorSet bas_out = new FadeExit();
//    private PayUtil payUtil = new PayUtil();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        initViewAndDate();
        getData();
    }

    private void getData() {
        getWallet();
    }

    //查询优惠券
    private void getPreferentialCoupon() {
        if (couponModel != null) {
            if (couponModel.getModelType() == ModelType.CASH) {
                if (TextUtils.isEmpty(numEdt.getText().toString())) {
                    count = 1;
                } else {
                    count = Integer.parseInt(numEdt.getText().toString());
                }
                appAction.getPreferentialCoupon(loginName, couponModelId, count, new CallbackListener<Map<String, List<CouponModel>>>() {
                    @Override
                    public void onSuccess(Map<String, List<CouponModel>> data) {
                        List<CouponModel> canUseData = data.get("canUse");
                        if (canUseData.size() > 0) {
                            emptyQuanLayout.setVisibility(View.GONE);
                            quanLayout.setVisibility(View.VISIBLE);
                            quanNumTxt.setText(getResources().getString(R.string.txt_have) + canUseData.size() + getResources().getString(R.string.txt_have_num));
                            canUseDataList = new String[canUseData.size()];
                            canUseDataIdList = new int[canUseData.size()];
                            for (int i = 0; i < canUseData.size(); i++) {
                                CouponModel couponModel = canUseData.get(i);
                                canUseDataList[i] = couponModel.getName();
                                canUseDataIdList[i] = couponModel.getId();
                                if (couponModel.getModelType() == ModelType.DISCOUNT) {//折扣券
                                    map.put(couponModel.getName(), DISCOUNT + ":" + String.valueOf(couponModel.getDiscount()));
                                }
                                if (couponModel.getModelType() == ModelType.VOUCHER) {//抵扣券
                                    map.put(couponModel.getName(), VOUCHER + ":" + String.valueOf(couponModel.getDebitAmount()));
                                }
                            }
                        } else {
                            emptyQuanLayout.setVisibility(View.VISIBLE);
                            quanLayout.setVisibility(View.GONE);
                        }
                        noEnoughMoney();
                        loadingLayout.setVisibility(View.GONE);
                    }

                    @Override
                    public void onFailure(String errorCode, String message) {
                        ToastUtil.showShort(PayActivity.this, R.string.toast_get_customer_wallet_fail);
                        reloadingLayout.setVisibility(View.VISIBLE);
                        loadingLayout.setVisibility(View.GONE);
                    }
                });
            } else {
                emptyQuanLayout.setVisibility(View.VISIBLE);
                quanLayout.setVisibility(View.GONE);
            }
        }
    }

    private void getTicket() {
        if (couponCategory == CustomerCouponCategory.CLIENT) {
            appAction.viewCustomerCoupon(couponModelId, new CallbackListener<CustomerCouponBO>() {
                @Override
                public void onSuccess(CustomerCouponBO data) {
                    if (data != null) {
                        customerCouponBO = data;
                        nameTxt.setText(data.getName());
                        priceTxt.setText(UseUtil.handlePrice(data.getPrice()));
                        getPriceCount();
                    } else {
                        ToastUtil.showShort(PayActivity.this, getResources().getString(R.string.toast_fail_get_data));
                    }
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    ToastUtil.showShort(PayActivity.this, R.string.toast_get_customer_wallet_fail);
                    reloadingLayout.setVisibility(View.VISIBLE);
                    loadingLayout.setVisibility(View.GONE);
                }
            });
        } else {
            appAction.viewCouponModel(couponModelId, loginName, channelId, new CallbackListener<CouponModel>() {
                @Override
                public void onSuccess(CouponModel data) {
                    if (data != null) {
                        couponModel = data;
                        nameTxt.setText(data.getName());
                        priceTxt.setText(UseUtil.handlePrice(data.getEstimateAmount()));
                        getPriceCount();
                    } else {
                        ToastUtil.showShort(PayActivity.this, getResources().getString(R.string.toast_fail_get_data));
                    }
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    ToastUtil.showShort(PayActivity.this, R.string.toast_get_customer_wallet_fail);
                    reloadingLayout.setVisibility(View.VISIBLE);
                    loadingLayout.setVisibility(View.GONE);
                }
            });
        }
    }

    private void initViewAndDate() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        couponModelId = getIntent().getIntExtra(COUPON_MODEL_ID, 0);
        couponCategory = (CustomerCouponCategory) getIntent().getSerializableExtra(COUPON_CATEGORY);
        if (couponModelId == 0) {
            ToastUtil.showShort(this, "error");
            finish();
        }

        loginName = UserInfoKeeper.readPhoneNumber(this);
        numEdt.setText(String.valueOf(1));
        quanLayout.setOnClickListener(this);
        miniusIbtn.setOnClickListener(this);
        plusIbtn.setOnClickListener(this);
        walletCheckIbtn.setOnClickListener(this);
        wechatCheckIbtn.setOnClickListener(this);
        alipayCheckIbtn.setOnClickListener(this);
        surePayBtn.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        numEdt.addTextChangedListener(this);
        isCheckIv.setOnClickListener(this);
        reloadingLayout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int num;
        if (!numEdt.getText().toString().equals(null) & !numEdt.getText().toString().equals("")) {
            num = Integer.parseInt(numEdt.getText().toString());
        } else {
            num = 1;
        }
        if (v == miniusIbtn) {
            miniusIbtn.setEnabled(false);
            if (num > 1) {
                numEdt.setText(String.valueOf(num - 1));
            }
            plusIbtn.setEnabled(true);
            if (couponModel != null) {//B端券
                getPreferentialCoupon();
            }
            getPriceCount();
        }
        if (v == plusIbtn) {
            plusIbtn.setEnabled(false);
            if (Integer.parseInt(numEdt.getText().toString()) >= 1000) {//一次最多可购买1000
                numEdt.setText("1000");
                priceCountTxt.setText(String.valueOf(1000 * Integer.parseInt(numEdt.getText().toString())));
                ToastUtil.showShort(this, getResources().getString(R.string.toast_purchase_num));
            }
            if (couponModel != null) {//B端
                if (couponModel.getIsLimit() == LimitType.LIMIT) {//限购的话，判断是不是超过限购数量
                    if (Integer.parseInt(numEdt.getText().toString()) >= couponModel.getLimitNumber()) {
                        plusIbtn.setEnabled(false);
                    } else {
                        isOverLimit = false;
                        numEdt.setText(String.valueOf(num + 1));
                        //现金券才需要查询优惠券信息
                        getPreferentialCoupon();
                        getPriceCount();
                    }
                } else if (Integer.parseInt(couponModel.getIssueCount()) - couponModel.getLockedCount() - couponModel.getSaleCount() <= Integer.parseInt(numEdt.getText().toString())) {//剩余数量为0
                    plusIbtn.setEnabled(false);
                } else {
                    numEdt.setText(String.valueOf(num + 1));
                    //现金券才需要查询优惠券信息
                    getPreferentialCoupon();
                    getPriceCount();
                }
            } else if (customerCouponBO != null) {//C端
                if (customerCouponBO.getType() == CustomerCouponType.SKILL) {
                    if (customerCouponBO.getIssueCount() - customerCouponBO.getLockedCount() - customerCouponBO.getSaleCount() <= Integer.parseInt(numEdt.getText().toString())) {//剩余数量为0
                        plusIbtn.setEnabled(false);
                    } else {
                        numEdt.setText(String.valueOf(num + 1));
                        getPriceCount();
                    }
                } else {
                    numEdt.setText(String.valueOf(num + 1));
                    getPriceCount();
                }
            }
        }
        if (v == walletCheckIbtn) {
            if (walletMoney < Double.parseDouble(priceCountTxt.getText().toString())) {
                walletCheckIbtn.setImageResource(R.drawable.ic_uncheck);
                ToastUtil.showShort(this, "余额不足");
                moneyText.setTextColor(getResources().getColor(R.color.bg_normal));
            } else {
                changeIcon(v);
            }
        }
        if (v == wechatCheckIbtn || v == alipayCheckIbtn) {
            changeIcon(v);
        }
        if (v == surePayBtn) {
            if (couponCategory == CustomerCouponCategory.CLIENT) {//C端券
                MobclickAgent.onEvent(PayActivity.this, "1012");
            } else {//B端券
                MobclickAgent.onEvent(PayActivity.this, "1011");
            }
            toPay();
        }
        if (v == backIbtn) {
            finish();
        }
        if (v == quanLayout) {
            MobclickAgent.onEvent(PayActivity.this, "1031");
            Intent intent = new Intent(this, WheelViewActivity.class);
            intent.putExtra(WheelViewActivity.DATAS, canUseDataList);
            intent.putExtra(WheelViewActivity.IDS, canUseDataIdList);
            intent.putExtra(WheelViewActivity.FLAG, UserActivity.flagSchool);
            startActivityForResult(intent, WheelViewActivity.CODE);
        }
        if (v == isCheckIv) {
            quanCheckLayout.setVisibility(View.GONE);
            quanId = 0;
            getPriceCount();
//            priceCountTxt.setText(UseUtil.handlePrice(Double.parseDouble(priceTxt.getText().toString()) * Double.parseDouble(numEdt.getText().toString())));
            noEnoughMoney();
        }
        if (v == reloadingLayout) {
            reloadingLayout.setVisibility(View.GONE);
            loadingLayout.setVisibility(View.VISIBLE);
            getData();
        }
    }

    //余额不足的时候，改变钱包支付样式
    private void noEnoughMoney() {
        if (walletMoney < Double.parseDouble(priceCountTxt.getText().toString())) {
            walletCheckIbtn.setImageResource(R.drawable.ic_uncheck);
            moneyText.setTextColor(getResources().getColor(R.color.bg_normal));
            //设置微信支付
            wechatCheckIbtn.setImageResource(R.drawable.ic_checked);
            payType = "wechat";
        } else {
            moneyText.setTextColor(getResources().getColor(R.color.text_price));
        }
    }

    private void toPay() {
        switch (payType) {
            case "wallet":
                confirmWalletDialog();
                break;
            case "wechat":
                if (Double.parseDouble(priceCountTxt.getText().toString()) > 0) {
                    if (couponModel != null) {//B端
                        createCouponOrderNow();
                    } else {
                        CClientPayByWechat();
                    }
                } else {
                    ToastUtil.showShort(this, getResources().getString(R.string.toast_nonsupport_wechat));
                }
                break;
            case "alipay":
                if (Double.parseDouble(priceCountTxt.getText().toString()) > 0) {
                    if (couponModel != null) {//B端
                        createCouponOrderNow();
                    } else {
                        CClientPayByAlipay();
                    }
                } else {
                    ToastUtil.showShort(this, getResources().getString(R.string.toast_nonsupport_aipay));
                }
                break;
        }
    }

    private void confirmWalletDialog() {
        final NormalDialog dialog = new NormalDialog(this);
        dialog.content(getResources().getString(R.string.dialog_sure_pay_by_wallet))
                .isTitleShow(false)
                .showAnim(bas_in)
                .dismissAnim(bas_out)
                .show();

        dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {
            @Override
            public void onBtnLeftClick() {
                if (couponCategory == CustomerCouponCategory.CLIENT) {//购买C端券
                    MobclickAgent.onEvent(PayActivity.this, "1013");
                    CClientPayByWallet();
                } else {//购买B端券
                    MobclickAgent.onEvent(PayActivity.this, "1014");
                    BClientPayByWallet();
                }
                dialog.dismiss();
            }
        });
        dialog.setOnBtnRightClickL(new OnBtnRightClickL() {
            @Override
            public void onBtnRightClick() {
                dialog.dismiss();
            }
        });
    }

  /*  //支付宝支付
    private void alipay() {
        String orderInfo = createAlipayInfo();
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        new Thread(new AlipayRunnable()).start();
    }*/

    /*private String sign(String orderInfo) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(Keys.PRIVATE));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(orderInfo.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String createAlipayInfo() {
        AlipayOrderInfoBuilder builder = new AlipayOrderInfoBuilder();
        if (couponModel != null) {
            builder.setOutTradeNo(orderNumber);
            builder.setSubject(couponModel.getName());
            builder.setBody(couponModel.getIntroduce());
        }
        if (customerCouponBO != null) {
            builder.setOutTradeNo(orderNumber);
            builder.setSubject(customerCouponBO.getName());
            builder.setBody(customerCouponBO.getIntroduce());
        }
        String price = UseUtil.handlePrice(Double.parseDouble(priceCountTxt.getText().toString()));
        builder.setTotalFee(price);
        String url = PropertiesUtil.getAlipayNotifyUrl();
        builder.setNotifyUrl(url);
        return builder.build();
    }

    private class AlipayRunnable implements Runnable {

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(PayActivity.this);
            // 调用支付接口
            try {
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = MESSAGE_ALIPAY;
                msg.obj = result;
                mAlipayHandler.sendMessage(msg);
            } catch (Exception e) {
                Log.d("test", e.toString());
            }
        }
    }

    Handler mAlipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            switch (msg.what) {
                case MESSAGE_ALIPAY:
                    String resultStatus = result.resultStatus;

                    // 判断resultStatus 为"9000"则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ToastUtil.showShort(PayActivity.this, "支付成功");
                        if (couponModel != null) {
                            showDialog(false);
                        } else if (customerCouponBO != null) {
                            showDialog(true);
                        }
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000" 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showShort(PayActivity.this, "支付结果确认中");
                        } else {
                            ToastUtil.showShort(PayActivity.this, "支付失败");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public String getSignType() {
        return "sign_type=\"RSA\"";
    }*/

    //购买B端券
    private void BClientPayByWallet() {
        if (couponModel.getEstimateAmount() == 0) {//0元券，不需要支付
            addFreeCoupon();
        } else {
            createCouponOrderNow();
        }
    }

    //非0元券创建订单
    private void createCouponOrderNow() {
        appAction.createCouponOrderNow(loginName, couponModelId, Integer.parseInt(numEdt.getText().toString()), channelId, quanId, new CallbackListener<OrderInfo>() {
            @Override
            public void onSuccess(OrderInfo data) {
                orderNumber = data.getNumber();
//                makeOrderToPaying(String.valueOf(data.getId()));
                if (payType.equals("wallet")) {
                    payByWallet();
                } else if (payType.equals("wechat")) {
                    payByWechat();
                } else if (payType.equals("alipay")) {
//                    alipay();
                    alipay(data.getId(), "", orderNumber, couponModelId, couponModel.getName(), couponModel.getIntroduce(), priceCountTxt.getText().toString(), PayActivity.this, true);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //购买B端0元券
    private void addFreeCoupon() {
        appAction.addFreeCoupon(couponModelId, loginName, Integer.parseInt(numEdt.getText().toString()), channelId, new CallbackListener<OrderInfo>() {
            @Override
            public void onSuccess(OrderInfo data) {
                showDialog(false);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //购买B端非0元券
    private void payByWallet() {
        appAction.payByWallet(orderNumber, loginName, payPass, new CallbackListener<OrderInfo>() {
            @Override
            public void onSuccess(OrderInfo data) {
                showDialog(false);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //通过支付宝购买C端券，生成订单
    private void CClientPayByAlipay() {
        appAction.createCustomerOrderByAliPay(loginName, customerCouponBO.getId(), Integer.parseInt(numEdt.getText().toString()), new CallbackListener<OrderInfo>() {
            @Override
            public void onSuccess(OrderInfo data) {
                orderNumber = data.getNumber();
//                alipay();
                alipay(data.getId(), "", orderNumber, couponModelId, customerCouponBO.getName(), customerCouponBO.getIntroduce(), priceCountTxt.getText().toString(), PayActivity.this, true);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //通过微信购买C端券，生成订单
    private void CClientPayByWechat() {
        appAction.createCustomerOrderByWxPay(loginName, customerCouponBO.getId(), Integer.parseInt(numEdt.getText().toString()), PropertiesUtil.getAppWechatKey(), PropertiesUtil.getMchid(), new CallbackListener<OrderInfo>() {
            @Override
            public void onSuccess(OrderInfo data) {
//                genSign(data.getPrepayId());
                UserInfoKeeper.writeState(PayActivity.this, false);
                UserInfoKeeper.writeOrderId(PayActivity.this, data.getId());
                UserInfoKeeper.writeKcuponModelId(PayActivity.this, couponModelId);
                UserInfoKeeper.writeWord(PayActivity.this, "");
                genSign(data.getPrepayId(), PayActivity.this);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //购买C端券
    private void CClientPayByWallet() {
        appAction.createCustomerOrder(loginName, payPass, couponModelId, Integer.parseInt(numEdt.getText().toString()), new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
                showDialog(false);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    //弹出购买成功券包
    private void showDialog(final boolean result) {
        String message;
        String title;
        if (result) {//c端
            title = getResources().getString(R.string.dialog_success_buy_C);
            message = getResources().getString(R.string.dialog_my_orders);
        } else {
            title = getResources().getString(R.string.dialog_success_buy_B);
            message = getResources().getString(R.string.dialog_my_tickets);
        }
        final NormalTipDialog dialog = new NormalTipDialog(PayActivity.this);
        dialog.content(title)//
                .isTitleShow(false)
                .btnText(message)//
//                .showAnim(bas_in)//
//                .dismissAnim(bas_out)//
                .show();
        dialog.setOnBtnClickL(new OnBtnClickL() {
            @Override
            public void onBtnClick() {
                if (result) {//C端
                    Intent intent = new Intent(PayActivity.this, MyOrderActivity.class);
                    startActivity(intent);
                } else {//B端
                    Intent intent = new Intent(PayActivity.this, MyTicketsActivity.class);
                    startActivity(intent);
                }
                dialog.dismiss();
//                finish();
            }
        });
    }

    private void getWallet() {
        appAction.getCustomerWallet(UserInfoKeeper.readPhoneNumber(this), new CallbackListener<WalletModel>() {
            @Override
            public void onSuccess(WalletModel data) {
//                moneyText.setText("(" + (data.getAmount() - data.getLockAmount()) + getResources().getString(R.string.txt_yuan) + ")");
                moneyText.setText("(￥" + (UseUtil.handlePrice(data.getAccount())) + ")");
                walletMoney = data.getAccount();
                loadingLayout.setVisibility(View.GONE);
                getTicket();
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(PayActivity.this, R.string.toast_get_customer_wallet_fail);
                reloadingLayout.setVisibility(View.VISIBLE);
                loadingLayout.setVisibility(View.GONE);
            }
        });
    }

    private void changeIcon(View v) {
        if (v == walletCheckIbtn) {
            payType = "wallet";
            walletCheckIbtn.setImageResource(R.drawable.ic_checked);
            wechatCheckIbtn.setImageResource(R.drawable.ic_uncheck);
            alipayCheckIbtn.setImageResource(R.drawable.ic_uncheck);
        }
        if (v == wechatCheckIbtn) {
            payType = "wechat";
            wechatCheckIbtn.setImageResource(R.drawable.ic_checked);
            walletCheckIbtn.setImageResource(R.drawable.ic_uncheck);
            alipayCheckIbtn.setImageResource(R.drawable.ic_uncheck);
        }
        if (v == alipayCheckIbtn) {
            payType = "alipay";
            alipayCheckIbtn.setImageResource(R.drawable.ic_checked);
            wechatCheckIbtn.setImageResource(R.drawable.ic_uncheck);
            walletCheckIbtn.setImageResource(R.drawable.ic_uncheck);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (isOverLimit) {
            String num = numEdt.getText().toString();
            if (num.trim().equals("")) {
                num = "1";
                isOverLimit = false;
            }
            if (Integer.parseInt(num) >= 1000) {//一次最多可购买1000
                isOverLimit = false;
                numEdt.setText("1000");
                priceCountTxt.setText(String.valueOf(1000 * Integer.parseInt(priceTxt.getText().toString())));
                ToastUtil.showShort(this, getResources().getString(R.string.toast_purchase_num));
            } else {
                if (couponModel != null) {
                    if (couponModel.getIsLimit() == LimitType.LIMIT) {//限购的话，判断是不是超过限购数量
                        if (Integer.parseInt(num) >= couponModel.getLimitNumber()) {
                            plusIbtn.setEnabled(false);
                            isOverLimit = false;
                            numEdt.setText(String.valueOf(couponModel.getLimitNumber()));
                        }
                        getPreferentialCoupon();
                        getPriceCount();
                    } else if (Integer.parseInt(couponModel.getIssueCount()) - couponModel.getLockedCount() - couponModel.getSaleCount() <= Integer.parseInt(num)) {//剩余数量为0
                        plusIbtn.setEnabled(false);
                        isOverLimit = false;
                        int number = Integer.parseInt(couponModel.getIssueCount()) - couponModel.getLockedCount() - couponModel.getSaleCount();
                        numEdt.setText(String.valueOf(number));
                    }
                    getPreferentialCoupon();
                    getPriceCount();
                } else {
                    if (customerCouponBO.getType() == CustomerCouponType.SKILL) {
                        if (customerCouponBO.getIssueCount() - customerCouponBO.getLockedCount() - customerCouponBO.getSaleCount() <= Integer.parseInt(num)) {//剩余数量为0
                            plusIbtn.setEnabled(false);
                            isOverLimit = false;
                            int number = customerCouponBO.getIssueCount() - customerCouponBO.getLockedCount() - customerCouponBO.getSaleCount();
                            numEdt.setText(String.valueOf(number));
                        }
                    }
                    getPriceCount();
//                    priceCountTxt.setText(UseUtil.handlePrice(Double.parseDouble(priceTxt.getText().toString()) * Double.parseDouble(num)));
                }
            }
        }
        isOverLimit = true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == WheelViewActivity.CODE) {
            Bundle b = data.getExtras();
            quanName = b.getString(WheelViewActivity.NAME);
            quanId = b.getInt(WheelViewActivity.ID);
            quanNameTxt.setText(quanName);
            quanCheckLayout.setVisibility(View.VISIBLE);
            getPriceCount();
        }
    }

    //计算总价格
    private void getPriceCount() {
      /*  //初始化总价
        String num = numEdt.getText().toString();
        String price = priceTxt.getText().toString();
        priceCountTxt.setText(UseUtil.handlePrice(Integer.parseInt(num) * Double.parseDouble(price)));
        if (value.indexOf(DISCOUNT) != -1) {
            value = value.substring(value.indexOf(":") + 1);
            preferentialPrice = Double.parseDouble(value) * 0.01;
            preferentialType = DISCOUNT;
            priceCount = Double.parseDouble(priceCountTxt.getText().toString()) * preferentialPrice;
        }
        if (value.indexOf(VOUCHER) != -1) {
            value = value.substring(value.indexOf(":") + 1);
            preferentialType = VOUCHER;
            preferentialPrice = Double.parseDouble(value);
            priceCount = Double.parseDouble(priceCountTxt.getText().toString()) - preferentialPrice;
        }
        if (priceCount >= 0) {
            priceCountTxt.setText(UseUtil.handlePrice(priceCount));
        } else {
            priceCountTxt.setText(UseUtil.handlePrice(0));
        }*/
        String num = numEdt.getText().toString();
        if (TextUtils.isEmpty(num)) {
            num = "1";
        }
        if (couponModel != null) {//B端券
            appAction.calcPrice(loginName, couponModelId, Integer.parseInt(num), quanId, new CallbackListener<Map<String, Object>>() {
                @Override
                public void onSuccess(Map<String, Object> data) {
                    plusIbtn.setEnabled(true);
                    miniusIbtn.setEnabled(true);
                    priceCountTxt.setText(UseUtil.handlePrice((Double) data.get("finalAmount")));
                    Log.d("test", data.get("finalAmount") + "");
                    if (couponModel.getModelType() == ModelType.CASH) {
                        getPreferentialCoupon();
                    }
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    ToastUtil.showShort(PayActivity.this, message);
                    surePayBtn.setEnabled(false);
                    plusIbtn.setEnabled(true);
                    miniusIbtn.setEnabled(true);
                }
            });
        } else if (customerCouponBO != null) {
            appAction.calcCustCouponPrice(customerCouponBO.getId(), Integer.parseInt(num), new CallbackListener<Double>() {
                @Override
                public void onSuccess(Double data) {
                    plusIbtn.setEnabled(true);
                    miniusIbtn.setEnabled(true);
                    priceCountTxt.setText(UseUtil.handlePrice(data));
                    noEnoughMoney();
                }

                @Override
                public void onFailure(String errorCode, String message) {
                    ToastUtil.showShort(PayActivity.this, message);
                    plusIbtn.setEnabled(true);
                    miniusIbtn.setEnabled(true);
                    surePayBtn.setEnabled(false);
                }
            });
        }
    }

    //微信支付
    private void payByWechat() {
        UserInfoKeeper.writeState(PayActivity.this, false);
        appAction.payAppOrderByWX(orderNumber, PropertiesUtil.getMchid(), PropertiesUtil.getAppWechatKey(), new CallbackListener<String>() {
            @Override
            public void onSuccess(String data) {
//                genSign(data);
                genSign(data, PayActivity.this);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(PayActivity.this, message);
            }
        });
    }

    /*private void genSign(String prepayId) {
        PayReq req = new PayReq();
        req.appId = PropertiesUtil.getAppWechatKey();
        req.partnerId = PropertiesUtil.getMchid();
        req.prepayId = prepayId;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(System.currentTimeMillis());
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req. packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams);
        IWXAPI msgApi = XYApplication.getWXAPI();
        msgApi.registerApp(PropertiesUtil.getAppWechatKey());
        if (isWXAppInstalledAndSupported(msgApi)) {
            msgApi.sendReq(req);
        }
    }*/

/*    private boolean isWXAppInstalledAndSupported(IWXAPI api) {
        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            ToastUtil.showShort(PayActivity.this, "微信客户端未安装，请确认");
        }

        return sIsWXAppInstalledAndSupported;
    }*/

    //生成签名
   /* private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(PropertiesUtil.getAppSecret());
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        Log.d("test", sb.toString());
        Log.d("test", appSign);
        return appSign;
    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()).toUpperCase();
    }*/


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("商城购买页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("商城购买页");
        MobclickAgent.onPause(this);
    }

    //支付宝支付
    private static final String ALGORITHM = "RSA";
    private static final String SIGN_ALGORITHMS = "SHA1WithRSA";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final int MESSAGE_ALIPAY = 0;
    private String payInfo;
    private Activity activity;
    private boolean mResult = false;
    private int orderId;
    private CustomerPayActivity customerPayActivity;

    public void alipay(int orderId,String word, String orderNumber,int couponModelId, String name, String introduction, String price, Context context, boolean result) {
        activity = (Activity) context;
        this.orderId = orderId;
        this.couponModelId = couponModelId;
        mResult = result;
        String orderInfo = createAlipayInfo(orderNumber, name, introduction, price);
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        new Thread(new AlipayRunnable()).start();
    }

    private String sign(String orderInfo) {
        try {
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(Keys.PRIVATE));
            KeyFactory keyf = KeyFactory.getInstance(ALGORITHM);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initSign(priKey);
            signature.update(orderInfo.getBytes(DEFAULT_CHARSET));
            byte[] signed = signature.sign();
            return Base64.encode(signed);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | UnsupportedEncodingException | SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String createAlipayInfo(String orderNumber, String name, String introduction, String price) {
        AlipayOrderInfoBuilder builder = new AlipayOrderInfoBuilder();
        builder.setOutTradeNo(orderNumber);
        builder.setSubject(name);
        builder.setBody(introduction);
//        String price = UseUtil.handlePrice(Double.parseDouble(priceCountTxt.getText().toString()));
        builder.setTotalFee(price);
        String url = PropertiesUtil.getAlipayNotifyUrl();
        builder.setNotifyUrl(url);
        return builder.build();
    }

    private class AlipayRunnable implements Runnable {

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(activity);
            // 调用支付接口
            try {
                String result = alipay.pay(payInfo);
                Message msg = new Message();
                msg.what = MESSAGE_ALIPAY;
                msg.obj = result;
                mAlipayHandler.sendMessage(msg);
            } catch (Exception e) {
                Log.d("test", e.toString());
            }
        }
    }

    Handler mAlipayHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            switch (msg.what) {
                case MESSAGE_ALIPAY:
                    String resultStatus = result.resultStatus;

                    // 判断resultStatus 为"9000"则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
//                        if (mResult) {//C端支付
//                            customerPayActivity = new CustomerPayActivity();
//                            customerPayActivity.confirmOreder(orderId,couponModelId,word,UserInfoKeeper.readPhoneNumber(activity));
//                        } else {
                        showDialog(false);
//                        }
                        ToastUtil.showShort(activity, "支付成功");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000" 代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            ToastUtil.showShort(activity, "支付结果确认中");
                        } else {
                            ToastUtil.showShort(activity, "支付失败");
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public String getSignType() {
        return "sign_type=\"RSA\"";
    }
    //支付宝支付END

    //微信支付
    public void genSign(String prepayId, Context context) {
        PayReq req = new PayReq();
        req.appId = PropertiesUtil.getAppWechatKey();
        req.partnerId = PropertiesUtil.getMchid();
        req.prepayId = prepayId;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(System.currentTimeMillis());
        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));
        req.sign = genAppSign(signParams);
        IWXAPI msgApi = XYApplication.getWXAPI();
        msgApi.registerApp(PropertiesUtil.getAppWechatKey());
        if (isWXAppInstalledAndSupported(msgApi, context)) {
            msgApi.sendReq(req);
        }
    }

    private boolean isWXAppInstalledAndSupported(IWXAPI api, Context context) {
        boolean sIsWXAppInstalledAndSupported = api.isWXAppInstalled()
                && api.isWXAppSupportAPI();
        if (!sIsWXAppInstalledAndSupported) {
            ToastUtil.showShort(context, "微信客户端未安装，请确认");
        }

        return sIsWXAppInstalledAndSupported;
    }

    //生成签名
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(PropertiesUtil.getAppSecret());
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes()).toUpperCase();
    }
    //微信支付END
}
